package it.clariter.web.action;

import java.io.InputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import it.clariter.dao.DocumentoDAO;
import it.clariter.model.Documento;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class EsportaListaAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		if(request.getSession().getAttribute("utente")==null){
			response.sendRedirect("login.jsp");
		}
		HttpSession session = request.getSession();
		
		Documento documento = (Documento) session.getAttribute("documentoPerRicerca");
		List<Documento> lista = new DocumentoDAO().findByExample(documento);
		
		ServletOutputStream outputstream = response.getOutputStream();
		ZipOutputStream out = new ZipOutputStream(outputstream);
		response.setHeader("Content-Disposition","attachment; filename=\"" + "documenti.zip" + "\"");
	    response.setContentType("application/zip");
		for(int i=0;i<lista.size();i++){
			if(lista.get(i).getDocumento()!=null) {
			Documento doc = lista.get(i);
			InputStream in = doc.getDocumento().getBinaryStream();
			byte[] data = new byte[1024]; 
				int count;
				// processo di compressione 
				out.putNextEntry(new ZipEntry(doc.getProtocollo()+".pdf"));
				while((count = in.read(data,0,1000)) != -1)
				{ 
					out.write(data, 0, count);
				}
			in.close();
			}
		}
		out.flush();
		out.close();
		outputstream.flush();
		out.flush();
		outputstream.close();
		out.close();
		return mapping.findForward("ok");

	}

}
